package com.study.sync;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wanghao
 * @version v1.0
 * @description: 可重入锁
 * @date 2021/12/27 15:58
 * @change [修改时间] [修改者]@[版本号] [修改内容说明]
 */
public class SyncLockDemo {

    public synchronized void add() {
        add();
    }

    public static void main(String[] args) {

        // lock演示可重入锁
        Lock lock = new ReentrantLock();
        // 创建线程
        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"外层");

                try {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName()+"内层");
                } finally {
                    //lock.unlock();
                }

            } finally {
                lock.unlock();
            }
        },"t1").start();

        // 创建新的线程
        new Thread(()->{
            lock.lock();
            System.out.println("tttt2");
            lock.unlock();
        },"t2").start();

        //new SyncLockDemo().add();

        // synchronized演示可重入锁
        /*Object o = new Object();
        new Thread(()->{
            synchronized (o) {
                System.out.println(Thread.currentThread().getName()+"外层");
                synchronized (o) {
                    System.out.println(Thread.currentThread().getName()+"中层");
                    synchronized (o) {
                        System.out.println(Thread.currentThread().getName()+"内层");

                    }
                }
            }
        },"t1").start();*/
    }
}
